package com.leoman.creator.service.impl;

import com.leoman.address.dao.AddressDao;
import com.leoman.address.entity.Address;
import com.leoman.city.dao.CityDao;
import com.leoman.common.controller.common.CommonController;
import com.leoman.common.service.impl.GenericManagerImpl;
import com.leoman.creator.dao.CreatorDao;
import com.leoman.creator.dao.CreatorImageDao;
import com.leoman.creator.entity.Creator;
import com.leoman.creator.entity.CreatorImage;
import com.leoman.creator.service.CreatorService;
import com.leoman.creatordynamic.dao.DynamicDao;
import com.leoman.creatordynamic.entity.Dynamic;
import com.leoman.entity.Configue;
import com.leoman.entity.FileBo;
import com.leoman.province.dao.ProvinceDao;
import com.leoman.user.dao.UserInfoDao;
import com.leoman.user.dao.UserLoginDao;
import com.leoman.user.entity.UserInfo;
import com.leoman.user.entity.UserLogin;
import com.leoman.utils.DateUtils;
import com.leoman.utils.FileUtil;
import com.leoman.utils.ImageUtil;
import com.leoman.work.dao.WorkCreatorDao;
import com.leoman.work.entity.WorkCreator;
import net.sf.json.JSONArray;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartRequest;

import java.io.IOException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by 蔡琦 on 2016/6/15 0015.
 */
@Service
public class CreatorServiceImpl extends GenericManagerImpl<Creator, CreatorDao> implements CreatorService {

    @Autowired
    private CreatorDao creatorDao;

    @Autowired
    private UserInfoDao userInfoDao;

    @Autowired
    private DynamicDao dynamicDao;

    @Autowired
    private ProvinceDao provinceDao;

    @Autowired
    private CityDao cityDao;

    @Autowired
    private CreatorImageDao creatorImageDao;

    @Autowired
    private AddressDao addressDao;

    @Autowired
    private WorkCreatorDao workCreatorDao;

    @Autowired
    private UserLoginDao userLoginDao;

    @Override
    public List<Creator> iFindList() {
        return creatorDao.findAll();
    }

    @Override
    @Transactional
    public Integer saveAll(Long id,
                           String nickname,
                           String password,
                           Integer gender,
                           Integer isCreator,
                           Long provinceId,
                           Long cityId,
                           String description,
                           String weibo,
                           String experience,
                           String[] time,
                           String[] thing,
                           String tempAddImageIds1,
                           String tempAddImageIds2,
                           String tempDelImageIds,
                           String[] times,
                           String[] things,
                           MultipartRequest multipartRequest) throws IOException, ParseException {
        String[] addImageIds1 = tempAddImageIds1.split(",");
        String[] addImageIds2 = tempAddImageIds2.split(",");
        String[] delImageIds = tempDelImageIds.split(",");

        UserInfo userInfo;
        Creator creator;
        List<UserInfo> userInfoList = userInfoDao.findAll();
        if (null == id) {
            // 判断昵称是否已存在
            for (UserInfo userInfo1 : userInfoList) {
                if (nickname.equals(userInfo1.getNickname())) {
                    // 昵称已存在
                    return 2;
                }
            }
            userInfo = new UserInfo();
            userInfo.setCreateDate(System.currentTimeMillis());
        } else {
            userInfo = userInfoDao.findOne(id);
            // 判断昵称是否已存在
            for (UserInfo userInfo1 : userInfoList) {
                if (nickname.equals(userInfo1.getNickname()) && !nickname.equals(userInfo.getNickname())) {
                    // 昵称已存在
                    return 2;
                }
            }
        }

        if (userInfo.getCreator() == null) {
            // 没有主创则新增
            creator = new Creator();
            creator.setCreateDate(System.currentTimeMillis());
        } else {
            // 有则编辑
            creator = userInfo.getCreator();
        }

        // 保存主创省份城市
        if (provinceId != null) {
            creator.setProvince(provinceDao.findOne(provinceId));
        }
        if (cityId != null) {
            creator.setCity(cityDao.findOne(cityId));
        }

        creator.setDescription(description);
        creator.setWeibo(weibo);
        creator.setExperience(experience);

        MultipartFile multipartFile2 = multipartRequest.getFile("imageFile2");
        if (null != multipartFile2) {
            FileBo fileBo = null;
            try {
                fileBo = FileUtil.save(multipartFile2, true);
            } catch (IOException e) {
                e.printStackTrace();
            }
            creator.setCoverUrl(fileBo.getPath());
            creator.setSuolue(fileBo.getSuoluePath());
        }

        // 主创获赞感谢音
        MultipartFile multipartFile1 = multipartRequest.getFile("url");
        if (null != multipartFile1) {
            FileBo fileBo = FileUtil.save(multipartFile1, false);
            creator.setAudioUrl(fileBo.getPath());
        }
        creatorDao.save(creator);

        userInfo.setNickname(nickname);
        //userInfo.setMobile(mobile);
        userInfo.setPassword(password);
        userInfo.setGender(gender);

        // 是否有登录信息，没有则新增，有则编辑
        UserLogin userLogin = userLoginDao.findByUsername(userInfo.getMobile());
        if (userLogin != null) {
            userLogin.setPassword(password);
            userLoginDao.save(userLogin);
        } else {
            if (StringUtils.isNotEmpty(userInfo.getMobile())) {
                userLogin = new UserLogin();
                userLogin.setPassword(password);
                userLogin.setUsername(userInfo.getMobile());
                userLoginDao.save(userLogin);
            }
        }

        // 保存头像
        MultipartFile multipartFile = multipartRequest.getFile("imageFile");
        if (null != multipartFile) {
            FileBo fileBo = FileUtil.save(multipartFile, true);
            userInfo.setAvater(fileBo.getPath());
            userInfo.setSuolue(fileBo.getSuoluePath());
        }
        userInfo.setCreator(creator);
        userInfo.setIsCreator(isCreator);
        userInfoDao.save(userInfo);

        //修改动态保存
        saveModifyDynamic(creator, times, things);

        //新增动态
        saveNewDynamic(creator, time, thing);

        // 保存剧照图片集合
        CreatorImage image;
        for (String imageId : addImageIds1) {
            if (null != imageId && !imageId.equals("")) {
                image = creatorImageDao.findOne(Long.parseLong(imageId));
                image.setCreator(creator);
                //image.setImage();
                image.setType(0);
                creatorImageDao.save(image);
            }
        }

        // 保存生活照图片集合
        CreatorImage image2;
        for (String imageId : addImageIds2) {
            if (null != imageId && !imageId.equals("")) {
                image2 = creatorImageDao.findOne(Long.parseLong(imageId));
                //image2.setImage();
                image2.setType(1);
                image2.setCreator(creator);

                creatorImageDao.save(image2);
            }
        }

        // 删除图片集合
        CreatorImage image3;
        for (String imageId : delImageIds) {
            if (null != imageId && !imageId.equals("")) {
                image3 = creatorImageDao.findOne(Long.parseLong(imageId));
                creatorImageDao.delete(image3);
            }
        }
        return 1;
    }

    @Override
    public void detail(Long userId, Model model) {
        List<Map<String, Object>> list = new ArrayList<>();
        UserInfo userInfo = userInfoDao.findOne(userId);
        if (StringUtils.isNotEmpty(userInfo.getAvater())) {
            userInfo.setAvater(ImageUtil.clearUploadUrl(userInfo.getAvater()));
        }

        Map<String, Object> map;

        // 主创今日动态
        List<Dynamic> dynamicList = dynamicDao.findListNew(CommonController.getYesterday().getTime(), CommonController.getToday().getTime(), userInfo.getCreator().getId());
        model.addAttribute("dynamicList", dynamicList);

        Creator creator = userInfo.getCreator();
        if (StringUtils.isNotEmpty(creator.getCoverUrl())) {
            creator.setCoverUrl(ImageUtil.clearUploadUrl(creator.getCoverUrl()));
        }
        if (StringUtils.isNotEmpty(creator.getAudioUrl())) {
            creator.setAudioUrl(ImageUtil.clearUploadUrl(creator.getAudioUrl()));
        }

        // 主创剧照或者生活照
        List<CreatorImage> creatorImageList = creatorImageDao.findByCreatorId(creator.getId());
        for (CreatorImage creatorImage : creatorImageList) {
            map = new HashMap<>();
            map.put("id", creatorImage.getId());
            map.put("type", creatorImage.getType());
            map.put("path", ImageUtil.clearUploadUrl(creatorImage.getImage()));

            list.add(map);
        }

        // 主创地址
        List<Address> addressList = addressDao.findByUserId(userInfo.getId());

        // 主创作品
        List<WorkCreator> workCreatorList = workCreatorDao.findByUserId(userId);
        model.addAttribute("workCreatorList", workCreatorList);

        model.addAttribute("userInfo", userInfo);
        model.addAttribute("addressList", addressList);
        model.addAttribute("creatorImageList", JSONArray.fromObject(list));
    }

    /**
     * 保存修改动态
     */
    public void saveModifyDynamic(Creator creator, String[] times, String[] things) throws ParseException {
        List<Dynamic> dynamicList = dynamicDao.findByCreatorId(creator.getId());
        if (dynamicList.size() > 0) {
            for (int i = 0; i < times.length; i++) {
                if (StringUtils.isNotEmpty(times[i])) {
                    dynamicList.get(i).setTime(DateUtils.stringToLong(times[i], "yyyy-MM-dd hh:mm:ss"));
                    dynamicList.get(i).setDate(times[i].substring(0, 11));
                    dynamicList.get(i).setCreator(creator);
                    dynamicList.get(i).setStatus(things[i]);

                    dynamicDao.save(dynamicList.get(i));
                }
            }
        }
    }

    /**
     * 保存新增动态
     */
    public void saveNewDynamic(Creator creator, String[] time, String[] thing) throws ParseException {
        for (int i = 0; i < time.length; i++) {
            if (StringUtils.isNotEmpty(time[i])) {
                Dynamic dynamic = new Dynamic();
                dynamic.setTime(DateUtils.stringToLong(time[i], "yyyy-MM-dd hh:mm:ss"));
                dynamic.setDate(time[i].substring(0, 11));
                dynamic.setCreator(creator);
                if (thing[i] != null) {
                    dynamic.setStatus(thing[i]);
                }
                dynamicDao.save(dynamic);
            }
        }
    }
}
